package fr.emse.tatiana.commands;


import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import fr.emse.tatiana.CorpusNavigationView;
import fr.emse.tatiana.corpus.Corpus;
import fr.emse.tatiana.replayable.ReplayableInput;
import fr.emse.tatiana.utils.WSFileDialog;

/**
 * Action to create a new replayable from a selected filter
 * 
 * @author dyke
 *
 */
public class ApplyFilterAction extends Action {
	private final IWorkbenchWindow window;
	private final String navigationId;
	private final String editorId;
	
	private static ApplyFilterAction instance;
	
	public static ApplyFilterAction getInstance() {
		return instance;
	}
	
	public ApplyFilterAction(IWorkbenchWindow window, String label, String editorId, String navigationId) {
		this.window = window;
		this.editorId = editorId;
		this.navigationId = navigationId;
        setText(label);
        // The id is used to refer to the action in a menu or toolbar
		setId(ICommandIds.CMD_FILTER);
        // Associate the action with a pre-defined command, to allow key bindings.
		//setActionDefinitionId(ICommandIds.CMD_FILTER);
		setImageDescriptor(fr.emse.tatiana.Activator.getImageDescriptor("/icons/sample2.gif"));
		this.setEnabled(false);
		instance = this;
	}
	

	public void displayWith(String path) throws PartInitException {
		Corpus c = ((CorpusNavigationView) window.getActivePage().findView(this.navigationId)).getSelectedCorpus();
		IEditorInput input = new ReplayableInput(path, c);
		window.getActivePage().openEditor(input, editorId);
	}
	
	@Override
	public void run() {
		if(window != null) {	
			try {
				IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("Tatiana");
				IFolder filters = project.getFolder("filters");
				try {
					filters.refreshLocal(IResource.DEPTH_INFINITE, null);
				} catch (CoreException e) {
					// TODO later : no filters is a problem :)
				}
				WSFileDialog dialog = new WSFileDialog(
						window.getShell(), 
						SWT.SINGLE, 
						"Choose a filter to create new replayable",
						filters,
						false,
						new String[]{"xml"},
						null); 
				dialog.hideFirstChildren();
				if (dialog.open()!=Window.OK) {
					return;
				}
			
				this.displayWith(dialog.getSingleResult().getLocation().toString());
				

			} catch (PartInitException e) {
				MessageDialog.openError(window.getShell(), "Error", "Error opening view:" + e.getMessage());
			}
		}
	}
}
